#include "aerTimer.hpp"
#include <cstdlib>

#ifdef AER_WINDOWS
# include <windows.h>
#else
# include <sys/time.h>
#endif


namespace aer {

Timer::Timer(bool bEnable)
    : m_bEnable(bEnable),
      m_startTime(0.0),
      m_frameTime(0.0),
      m_elapsedTime(0.0),
      m_lastFPSTime(0.0),
      m_currentFPS(-1),
      m_frameCount(0u),
      m_totalFrameCount(0u)
{
  if (m_bEnable) {
    start();
  }
}


void Timer::start()
{
  m_startTime = getAbsoluteTime();  
  m_bEnable = true;
}
    
void Timer::update()
{
  if (!isEnable()) {
    return;
  }
  
  double lastFrameTime = m_frameTime;
  
  m_frameTime = getRelativeTime();
  m_elapsedTime = m_frameTime - lastFrameTime;  
  m_frameCount += 1u;
  ++m_totalFrameCount;
  
  if ((m_frameTime - m_lastFPSTime) >= 1000.0)
  {
    m_lastFPSTime = m_frameTime;
    m_currentFPS = m_frameCount;
    m_frameCount = 0u;
  }
}



double Timer::getAbsoluteTime() const
{    
  double appTime = 0.0;
    
# ifdef AER_WINDOWS
  
  LARGE_INTEGER ticksPerSecond;
  LARGE_INTEGER t;

  QueryPerformanceFrequency( &ticksPerSecond );
  QueryPerformanceCounter( &t );

  appTime = (t.QuadPart / ticksPerSecond.QuadPart) * 1000.0;

# else // AER_UNIX && AER_MACOS
    
  timeval t;
  gettimeofday( &t, NULL);
  appTime = t.tv_sec * 1000.0 + t.tv_usec * 0.001;
    
# endif
  
  return appTime;
}

} // aer
